package com.groupbuying.settleproducer.service.impl;

import com.groupbuying.settleproducer.connector.StoreFeign;
import com.groupbuying.settleproducer.connector.SysconfigFeign;
import com.groupbuying.settleproducer.connector.YSFeign;
import com.groupbuying.settleproducer.constants.*;
import com.groupbuying.settleproducer.domain.SettleUshopFlowStoreDO;
import com.groupbuying.settleproducer.domain.SettleUshopWithdrawalDO;
import com.groupbuying.settleproducer.domain.SettleUshopWithdrawalYsSecondClearDO;
import com.groupbuying.settleproducer.dto.*;
import com.groupbuying.settleproducer.service.SettleUshopFlowStoreService;
import com.groupbuying.settleproducer.service.SettleUshopPaymentService;
import com.groupbuying.settleproducer.service.SettleUshopWithdrawalService;
import com.groupbuying.settleproducer.service.SettleUshopWithdrawalYsSecondClearService;
import com.groupbuying.settleproducer.utils.DateUtils;
import com.groupbuying.settleproducer.utils.JsonUtils;
import com.groupbuying.settleproducer.utils.apiresult.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: WANGNING
 * @Email wyn20140226@aliyun.com
 * @Date: 2019/6/3 16:01
 * @Des 银盛二清代打款业务处理接口
 */
@Service
public class SettleUshopPaymentServiceImpl implements SettleUshopPaymentService {
    public static final Logger logger = LoggerFactory.getLogger(SettleUshopPaymentServiceImpl.class);
    @Autowired
    private YSFeign ysFeign;
    @Autowired
    private SysconfigFeign sysconfigFeign;
    @Autowired
    private StoreFeign storeFeign;
    @Autowired
    private SettleUshopWithdrawalYsSecondClearService withdrawalYsSecondClearService;
    @Autowired
    private SettleUshopWithdrawalService settleWithdrawalService;
    @Autowired
    private SettleUshopFlowStoreService settleUshopFlowStoreService;
    @Override
    public ApiResult createWithdrawal(Map<String, Object> map) {
        // 解析map参数---商户号
        Object tempParam = map.get("storeUuid");
        String counterId = tempParam == null ? null : tempParam.toString();
        // 解析map参数---商户生成的订单号
        String outTradeNo = DateUtils.format(new Date(), "yyyyMMdd")+counterId;
        // 解析map参数---商户日期
        String shopdate = DateUtils.format(new Date(), "yyyyMMdd");
        //获取提现id
        String withdrawalId=this.sysconfigFeign.getWithdrawalId();
        // 解析map参数---业务代码
        String businessCode = this.sysconfigFeign.getBusinessCode();
        // 解析map参数---币种CNY
        String currency = SettleUshopYSWithdrawalQueryEnumConstants.ENUM_CURRENCY_CNY;
        // 解析map参数---代付的总金额
        tempParam = map.get("totalAmount");
        String amount = tempParam == null ? null : tempParam.toString();
        BigDecimal totalAmount=new BigDecimal(amount);
        // 解析map参数---订单说明
        tempParam = map.get("subject");
        String subject = tempParam == null ? null : tempParam.toString();
        // 解析map参数---银盛报备商户号
        tempParam = map.get("ysUserCode");
        String merchantUsercode = tempParam == null ? null : tempParam.toString();
        /*-----------获取该商户的银行卡信息---------*/
        // 解析map参数---银行名称
        tempParam = map.get("bankName");
        String bankName = tempParam == null ? null : tempParam.toString();
        // 解析map参数---开户行所在城市
        tempParam = map.get("cityName");
        String cityName = tempParam == null ? null : tempParam.toString();
        // 解析map参数---银行帐号
        tempParam = map.get("bankno");
        String bankAccountNo = tempParam == null ? null : tempParam.toString();
        // 解析map参数---银行帐号用户名
        tempParam = map.get("bankAccountNo");
        String bankAccountName = tempParam == null ? null : tempParam.toString();
        // 解析map参数---收款方银行账户类型corporate :对公账户;personal:对私账户
        tempParam = map.get("bankAccountType");
        String bankAccountType = tempParam == null ? null : tempParam.toString();
        // 解析map参数---支持卡类型debit:借记卡;credit:信用卡 unit:单位结算卡
        tempParam = map.get("bankCardType");
        String bankCardType = tempParam == null ? null : tempParam.toString();
        //判断请求参数不为空
        if (StringUtils.isEmpty(counterId) || StringUtils.isEmpty(outTradeNo) || StringUtils.isEmpty(shopdate)|| StringUtils.isEmpty(businessCode)|| StringUtils.isEmpty(businessCode)
                || StringUtils.isEmpty(currency)|| StringUtils.isEmpty(subject)|| StringUtils.isEmpty(bankName)
                || StringUtils.isEmpty(cityName)|| StringUtils.isEmpty(bankAccountNo)|| StringUtils.isEmpty(bankAccountName)|| StringUtils.isEmpty(bankAccountType)
                || StringUtils.isEmpty(bankAccountType)||StringUtils.isEmpty(bankCardType)) {
            logger.info("SettleUshopPaymentServiceImpl-->createWithdrawal failure!----->银盛代代打款请求参数为空，请认真核实！");
            return ApiResult.paramIsNull();
        }
        try {
            int withdrawalYsSecondClearStatus =0;
            SettleUshopWithdrawalYsSecondClearDO withdrawalYsSecondClear=new SettleUshopWithdrawalYsSecondClearDO();
            SettleUshopWithdrawalDO settleWithdrawal = new SettleUshopWithdrawalDO();
            SettleUshopFlowStoreDO settleUshopFlowStoreDO=new SettleUshopFlowStoreDO();
            //提现平台账户金额
            BigDecimal count=this.settleUshopFlowStoreService.getSumByStoreId(counterId);
            //判断提现金额
            if(totalAmount.compareTo(count)<=0){
                //请求银盛提现接口
                YSPaymentDTO ysPaymentDTO=new YSPaymentDTO();
                ysPaymentDTO.setBank_account_no(bankAccountNo);
                ysPaymentDTO.setCurrency(currency);
                ysPaymentDTO.setOut_trade_no(outTradeNo);
                ysPaymentDTO.setShopdate(shopdate);
                ysPaymentDTO.setSubject(subject);
                ysPaymentDTO.setTotal_amount(totalAmount);
                ysPaymentDTO.setBank_card_type(bankCardType);
                ysPaymentDTO.setBank_account_type(bankAccountType);
                ysPaymentDTO.setBank_account_name(bankAccountName);
                ysPaymentDTO.setBank_city(cityName);
                ysPaymentDTO.setBank_name(bankName);
                String ysWithdrawalJSON= JsonUtils.toJSon(ysPaymentDTO);
                Map<String,Object> ysSplitReceiptMap=new ConcurrentHashMap<String,Object>();
                ysSplitReceiptMap.put("biz_content", ysWithdrawalJSON);
                /*调用银盛带打款*/
                String transferAccounts=ysFeign.transferAccounts(ysSplitReceiptMap);
                if(transferAccounts!=null&& transferAccounts.length() != 0){
                    Map<String ,Object> withdrawalRealMap= JsonUtils.jsonToMap(transferAccounts);
                    //解析返回来参数信息
                    String outTradeNos=(String)withdrawalRealMap.get("out_trade_no");
                    String TradeStatus=(String)withdrawalRealMap.get("trade_status");
                    String tadeStatusDescription=(String) withdrawalRealMap.get("trade_status_description");
                    String totalPrice=(String)withdrawalRealMap.get("total_amount");
                    String accountDate=(String)withdrawalRealMap.get("account_date");
                    String tradeNo=(String)withdrawalRealMap.get("trade_no");
                    String fee=(String)withdrawalRealMap.get("fee");
                    String partnerFee=(String)withdrawalRealMap.get("partner_fee");
                    String payeeFee=(String)withdrawalRealMap.get("payee_fee");
                    String payerFee=(String)withdrawalRealMap.get("payer_fee");
                    YSWithdrawalRealDTO ysWithdrawalRealDTO= (YSWithdrawalRealDTO) JsonUtils.convertBean(transferAccounts, YSWithdrawalRealDTO.class);
                    //判断请求参数不为空
                    if (StringUtils.isEmpty(outTradeNos) && StringUtils.isEmpty(TradeStatus)&&StringUtils.isEmpty(partnerFee)&&StringUtils.isEmpty(payeeFee) && StringUtils.isEmpty(payerFee)) {
                        logger.info("SettleUshopPaymentServiceImpl-->createWithdrawal failure!----->银盛代打款返回参数为空，请认真核实！");
                        return ApiResult.paramIsNull();
                    }
                    //生成提现信息
                    settleWithdrawal.setId(withdrawalId);
                    settleWithdrawal.setCounterId(counterId);
                    settleWithdrawal.setTotalPrice(totalAmount);
                    settleWithdrawal.setWithdrawalType(SettleWithdrawalEnumConstants.ENUM_WITHDRAWALTYPE_NOFIRST);
                    String serviceFee=this.sysconfigFeign.getFeeReplace();
                    settleWithdrawal.setServiceFee(new BigDecimal(serviceFee));
                    settleWithdrawal.setWithdrawalPrice(totalAmount);
                    settleWithdrawal.setPaycompanyBalance(new BigDecimal("0.00"));
                    settleWithdrawal.setWithdrawalState(SettleWithdrawalEnumConstants.ENUM_WITHDRAWALSTATE_WAIT);
                    settleWithdrawal.setGmtCreate(new Date());
                    settleWithdrawal.setGmtModified(new Date());
                    settleWithdrawal.setIsDelete(SettleWithdrawalEnumConstants.ENUM_ISDELETE_UNDEL);
                    int settleWithdrawalStatus=this.settleWithdrawalService.save(settleWithdrawal);
                    if(settleWithdrawalStatus>0){
                        withdrawalYsSecondClear.setCounterId(counterId);
                        withdrawalYsSecondClear.setSplitState(WithdrawalYsSecondClearEnumConstants.ENUM_SPLITSTATE_SUC);
                        withdrawalYsSecondClear.setWithdrawalPrice(totalAmount);
                        withdrawalYsSecondClear.setWithdrawalId(withdrawalId);
                        withdrawalYsSecondClear.setGmtCreate(new Date());
                        withdrawalYsSecondClear.setGmtModified(new Date());
                        withdrawalYsSecondClear.setIsDelete(SettleWithdrawalEnumConstants.ENUM_ISDELETE_UNDEL);
                        withdrawalYsSecondClearStatus=this.withdrawalYsSecondClearService.save(withdrawalYsSecondClear);
                        if(withdrawalYsSecondClearStatus>0){
                            settleWithdrawal.setWithdrawalState(SettleWithdrawalEnumConstants.ENUM_WITHDRAWALSTATE_SUC);
                            logger.info("SettleUshopPaymentServiceImpl-->createWithdrawal failure!----->银盛代打款表更改状态");
                            /*插入一条提现记录到分账商户子表中--提现金额为负数*/
                            settleUshopFlowStoreDO.setAmount(totalAmount.multiply(new BigDecimal("-1")));
                            settleUshopFlowStoreDO.setStoreId(counterId);
                            settleUshopFlowStoreDO.setExternalId(withdrawalId);
                            settleUshopFlowStoreDO.setGmtCreate(new Date());
                            settleUshopFlowStoreDO.setGmtModified(new Date());
                            settleUshopFlowStoreDO.setIsDelete(SettleWithdrawalEnumConstants.ENUM_ISDELETE_UNDEL);
                            settleUshopFlowStoreDO.setFlowType(SettleUshopFlowStoreEnumConstants.ENUM_FLOWTYPE_WITHDRAWAL);
                            settleUshopFlowStoreDO.setNote(SettleUshopFlowStoreEnumConstants.ENUM_WITHDRAWAL_NODE);
                            settleUshopFlowStoreDO.setId(sysconfigFeign.getFlowId());
                            this.settleUshopFlowStoreService.save(settleUshopFlowStoreDO);
                            this.settleWithdrawalService.update(settleWithdrawal);
                            logger.info("SettleUshopPaymentServiceImpl-->createWithdrawal success!");
                            return ApiResult.success();
                        }else{
                            settleWithdrawal.setWithdrawalState(SettleWithdrawalEnumConstants.ENUM_WITHDRAWALSTATE_EXC);
                            withdrawalYsSecondClear.setSplitState(WithdrawalYsSecondClearEnumConstants.ENUM_SPLITSTATE_FAIL);
                            this.withdrawalYsSecondClearService.update(withdrawalYsSecondClear);
                            this.settleWithdrawalService.update(settleWithdrawal);
                            logger.info("SettleUshopPaymentServiceImpl-->createWithdrawal failure!------>提现异常!");
                            return ApiResult.failure("提现异常!");
                        }
                    }
                }else{
                    //非一清代打款异常---调用代打款查询
                    Map<String, Object> paymentlMap = new HashMap<>();
                    YSPaymentQueryDTO ysPaymentQueryDTO = new YSPaymentQueryDTO();
                    ysPaymentQueryDTO.setOut_trade_no(outTradeNo);
                    ysPaymentQueryDTO.setShopdate(shopdate);
                    String ysWithdrawalJson = JsonUtils.beanToJson(ysPaymentQueryDTO);
                    paymentlMap.put("biz_content", ysWithdrawalJson);
                    String paymentJson=this.ysFeign.paymentQuery(paymentlMap);
                    logger.info("SettleUshopYSWithdrawalServiceImpl-->createFirstWithdrawal success!银盛非一清代打款查询结果------>" + paymentJson);
                    return ApiResult.success(paymentJson);
                }

            }else{
                logger.info("SettleUshopPaymentServiceImpl-->createWithdrawal failure!----->update(金额不足，请重新输入金额)");
                return ApiResult.failure(0, "金额不足，请重新输入金额", totalAmount);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            logger.error("SettleUshopPaymentServiceImpl-->createWithdrawal get Rules fail",e);
        }
        return ApiResult.failure();
    }
}
